/*
 * @(#)Patient.java 1.0.0 27/05/2014 *
 * INTRODUCCION A APLICACIONES J2EE
 * Ing. Darwin Rodrigo Zottola Pareja
 * rodrigozeta@gmail.com - twitter @Monozeta
 */
package com.unt.javawebunt.dao;

import java.io.Serializable;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.LockOptions;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.util.PropertiesHelper;

import com.unt.javawebunt.exception.DataAccessLayerException;
import com.unt.javawebunt.util.ExceptionHelper;
import com.unt.javawebunt.util.HibernateUtil;

/**
 * Clase que encapsula los metodos mas comunes en un dao, se usa desde los daos
 * particularizados para simplificar el acceso a datos.
 * 
 * @author dzottola
 * @version 1.0
 * @since 09/10/2012
 * @param <T>
 * @param <ID>
 */
public class GenericDAOImpl<T, ID extends Serializable> implements
		IGenericDAO<T, ID> {

	private Class<T> persistentClass;

	public static final Integer INSERT_ERROR = 1001;
	public static final Integer UPDATE_ERROR = 1002;
	public static final Integer DELETE_ERROR = 1003;
	public static final Integer FIND_ERROR = 1004;

	private static Logger log = Logger.getLogger(GenericDAOImpl.class);

	public GenericDAOImpl(Class<T> type) {
		this.persistentClass = type;
	}

	/**
	 * Metodo generico para guardar un objeto.
	 */
	@SuppressWarnings("unchecked")
	public ID save(T entity) throws DataAccessLayerException {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		ID id;
		try {
			id = (ID) session.save(entity);

			tx.commit();
		} catch (HibernateException e) {
			HibernateUtil.rollback(tx);
			log.error("HibernateException-Message[" + e.getMessage()
					+ "]-Set DEBUG mode for complete stacktrace.");
			log.debug(ExceptionHelper.getStackTrace(e));
			;
			throw new DataAccessLayerException(INSERT_ERROR, e);
		} catch (Exception e) {
			log.error("An exception has been raised - Message["
					+ e.getMessage()
					+ "]-Set DEBUG mode for complete stacktrace.");
			log.debug(ExceptionHelper.getStackTrace(e));
			;

			throw new DataAccessLayerException(INSERT_ERROR, e);
		}

		return id;
	}

	/**
	 * Metodo generico para actualizar un objeto.
	 */
	public void update(T entity) throws DataAccessLayerException {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();

		try {
			session.update(entity);
			tx.commit();
		} catch (HibernateException e) {
			HibernateUtil.rollback(tx);
			log.error("HibernateException-Message[" + e.getMessage()
					+ "]-Set DEBUG mode for complete stacktrace.");
			log.debug(ExceptionHelper.getStackTrace(e));
			;
			throw new DataAccessLayerException(UPDATE_ERROR, e);
		} catch (Exception e) {
			log.error("An exception has been raised - Message["
					+ e.getMessage()
					+ "]-Set DEBUG mode for complete stacktrace.");
			log.debug(ExceptionHelper.getStackTrace(e));
			;

			throw new DataAccessLayerException(UPDATE_ERROR, e);
		}
	}

	/**
	 * Metodo generico para borrar un objeto.
	 */
	public void delete(T entity) throws DataAccessLayerException {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();

		try {
			session.delete(entity);
			tx.commit();
		} catch (HibernateException e) {
			HibernateUtil.rollback(tx);
			log.error("HibernateException-Message[" + e.getMessage()
					+ "]-Set DEBUG mode for complete stacktrace.");
			log.debug(ExceptionHelper.getStackTrace(e));
			;
			throw new DataAccessLayerException(DELETE_ERROR, e);

		} catch (Exception e) {
			log.error("An exception has been raised - Message["
					+ e.getMessage()
					+ "]-Set DEBUG mode for complete stacktrace.");
			log.debug(ExceptionHelper.getStackTrace(e));
			;

			throw new DataAccessLayerException(DELETE_ERROR, e);
		}
	}

	/**
	 * Generic Method find by Id.
	 */
	@SuppressWarnings("unchecked")
	public T findById(ID id, boolean lock) throws DataAccessLayerException {
		T entity = null;

		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		try {
			if (lock) {
				entity = (T) session.get(getPersistentClass(), id,
						LockOptions.UPGRADE);
			} else {
				entity = (T) session.get(getPersistentClass(), id);
			}
			tx.commit();
		} catch (HibernateException e) {
			HibernateUtil.rollback(tx);
			log.error("HibernateException-Message[" + e.getMessage()
					+ "]-Set DEBUG mode for complete stacktrace.");
			log.debug(ExceptionHelper.getStackTrace(e));
			;
			throw new DataAccessLayerException(FIND_ERROR, e);
		}
		return entity;
	}

	/**
	 * Generic Method - return a list of all entities with an order.
	 */
	public List<T> findAll(Order order) throws DataAccessLayerException {
		return findByCriteria(order);
	}

	/**
	 * Retorna todos los datos de la clase parametrizada que coincidan con la
	 * criteria dada.
	 * 
	 * @param order
	 * @param criterionList
	 * @return
	 * @throws DataAccessLayerException
	 */
	@SuppressWarnings("unchecked")
	public List<T> findByCriteria(Order order, List<Criterion> criterionList)
			throws DataAccessLayerException {
		Criteria crit = null;
		List<T> resultado = null;

		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		try {

			crit = session.createCriteria(getPersistentClass());
			for (Criterion c : criterionList) {
				crit.add(c);
			}
			crit.addOrder(order);

			resultado = crit.list();
			tx.commit();
		} catch (HibernateException e) {
			HibernateUtil.rollback(tx);
			log.error("HibernateException-Message[" + e.getMessage()
					+ "]-Set DEBUG mode for complete stacktrace.");
			log.debug(ExceptionHelper.getStackTrace(e));
			;
			throw new DataAccessLayerException(FIND_ERROR, e);
		}
		return resultado;
	}

	/**
	 * Return all entities matching criteria
	 * 
	 * @param order
	 * @param criterionList
	 * @return
	 * @throws DataAccessLayerException
	 */
	@SuppressWarnings("unchecked")
	public List<T> findByCriteria(Order order, Criterion... criterion)
			throws DataAccessLayerException {
		Criteria crit = null;
		List<T> resultado = null;

		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		try {

			crit = session.createCriteria(getPersistentClass());
			for (Criterion c : criterion) {
				crit.add(c);
			}
			crit.addOrder(order);
			resultado = crit.list();
			tx.commit();
		} catch (HibernateException e) {
			HibernateUtil.rollback(tx);
			log.error("HibernateException-Message[" + e.getMessage()
					+ "]-Set DEBUG mode for complete stacktrace.");
			log.debug(ExceptionHelper.getStackTrace(e));
			;
			throw new DataAccessLayerException(FIND_ERROR, e);
		}
		return resultado;
	}

	protected Class<T> getPersistentClass() {
		return persistentClass;
	}

	/**
	 * Metodo generico para realizar un insert or update del objeto.
	 */
	public void saveOrUpdate(T entity) throws DataAccessLayerException {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		try {
			session.saveOrUpdate(entity);

			tx.commit();
		} catch (HibernateException e) {
			HibernateUtil.rollback(tx);
			log.error("HibernateException-Message[" + e.getMessage()
					+ "]-Set DEBUG mode for complete stacktrace.");
			log.debug(ExceptionHelper.getStackTrace(e));
			;
			throw new DataAccessLayerException(INSERT_ERROR, e);
		} catch (Exception e) {
			log.error("An exception has been raised - Message["
					+ e.getMessage()
					+ "]-Set DEBUG mode for complete stacktrace.");
			log.debug(ExceptionHelper.getStackTrace(e));
			;

			throw new DataAccessLayerException(INSERT_ERROR, e);
		}

	}

	/**
	 * Return the number of all entities matching criteria
	 * 
	 * @param order
	 * @param criterionList
	 * @return
	 * @throws DataAccessLayerException
	 * <br>
	 * @author dzottola
	 * @since 26-06-2012 <br>
	 */
	public Long countByCriteria(Order order, Criterion... criterionList)
			throws DataAccessLayerException {
		Criteria crit = null;
		Long count = null;

		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		try {

			crit = session.createCriteria(getPersistentClass());

			for (Criterion c : criterionList) {
				crit.add(c);
			}

			count = (Long) crit.addOrder(order)
					.setProjection(Projections.rowCount()).uniqueResult();
			tx.commit();
		} catch (HibernateException e) {
			HibernateUtil.rollback(tx);
			log.error("HibernateException-Message[" + e.getMessage()
					+ "]-Set DEBUG mode for complete stacktrace.");
			log.debug(ExceptionHelper.getStackTrace(e));
			throw new DataAccessLayerException(FIND_ERROR, e);
		}
		return count;
	}
}
